#!/usr/bin/env python3
import paramiko
import time
import telnetlib,sys
import xlrd
import threading
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
import time
import socket
import re

listenip = []
	
def ftpserver(ip):
	authorizer = DummyAuthorizer()
	authorizer.add_user('admin', '123456', '.', perm='elradfmw')
	handler = FTPHandler
	handler.authorizer = authorizer
	server = FTPServer((ip, 21), handler)
	server.serve_forever()

class ftpThread(threading.Thread):
	def __init__(self, threadID, name, x):
		threading.Thread.__init__(self)
		self.threadID = threadID
		self.name = name
		self.x = x

	def run(self):
		ftpserver("0.0.0.0")
		
def get_dev(colum):
	f = xlrd.open_workbook('device.xls')
	tables = f.sheet_by_index(0)
	device_list = []
	x = 1
	while True:
		try:
			data = tables.cell(x,colum)
			x += 1
			data = str(data)
			device_list.append(data[6:][:-1])
		except IndexError:
			break
	print('devices：')
	for i in device_list:
		print(i)
	return device_list
	
address = socket.getaddrinfo(socket.gethostname(),None)
ip = ''
serverip = ''
for item in address:
	if ':' not in item[4][0]:
		ip = item[4][0]
		try:
			ip = re.search(r'169.254.\d*' , str(ip)).group()
		except AttributeError:
			if ip != '':
				listenip.append(ip)
			serverip = ip
			print(serverip)
i = 1
'''
for x in listenip:
	locals()['thread' + str(i)] = ftpThread(i, "Thread-%s" % i, x)
	locals()['thread' + str(i)].setDaemon(True)
	locals()['thread' + str(i)].start()
	locals()['thread' + str(i)].join(timeout=1)
	#i = i+1
	'''
locals()['thread' + str(i)] = ftpThread(i, "Thread-%s" % i, i)
locals()['thread' + str(i)].setDaemon(True)
locals()['thread' + str(i)].start()
locals()['thread' + str(i)].join(timeout=1)	

devlist = get_dev(1)
userlist = get_dev(2)
passlist = get_dev(3)
index = 0
for dev in devlist:
	cfgname = 'vrpcfg.zip'
	try:
		tn=telnetlib.Telnet(dev,port=23,timeout=3)
	except OSError:
		print("无法访问目标设备")
		continue
	print(tn.read_until(b'Username:',1).decode('ascii'))
	print(tn.read_until(b'login:',1).decode('ascii'))
	name = userlist[index]
	passwd = passlist[index]
	tn.write(str.encode(name))
	tn.write(b'\n')
	print(tn.read_until(b'Password:',1).decode('ascii'))
	tn.write(str.encode(passwd))
	tn.write(b'\n')
	time.sleep(1)
	tn.write(b'dir\n ')
	time.sleep(1)
	result = tn.read_very_eager().decode('utf-8')
	print('dir*********' + result)	
	y = re.search(r'startup.cfg',result)
	if y != None:
		print('H3C')
		cfgname = y.group()
		print('配置文件是：' + cfgname)
	else:
		y = re.search(r'vrpcfg.zip',result)
		if y != None:
			print('huawei')
			cfgname = y.group()
			print('配置文件是：' + cfgname)
		else:
			print('没有找到配置文件！')
			cfgname = ''
	cmd = "ftp " + serverip + "\n"
	tn.write(cmd.encode("utf-8"))
	print(tn.read_until(b'(none)):',1).decode('gb2312'))
	tn.write(b'admin\n')	
	time.sleep(1)
	result = tn.read_very_eager().decode('gb2312')
	print(result)
	print(tn.read_until(b'password:',1).decode('gb2312'))
	tn.write(b'123456\n')
	print(tn.read_until(b'ftp]',1).decode('gb2312'))
	print(tn.read_until(b'ftp>',1).decode('gb2312'))
	put_cli = 'put ' + cfgname + '\n'
	tn.write(put_cli.encode("utf-8"))
	print(tn.read_until(b'seconds',1).decode('gb2312'))
	tn.close()
	print(ip,'finish!')
	index = index +1